package cn.ruanyun.backInterface.modules.business.withdrawDeposit.serviceimpl;

import cn.ruanyun.backInterface.common.constant.CommonConstant;
import cn.ruanyun.backInterface.common.enums.AddOrSubtractTypeEnum;
import cn.ruanyun.backInterface.common.pay.dto.TransferDto;
import cn.ruanyun.backInterface.common.pay.service.IPayService;
import cn.ruanyun.backInterface.common.utils.ResultUtil;
import cn.ruanyun.backInterface.common.vo.Result;
import cn.ruanyun.backInterface.modules.base.mapper.mapper.UserMapper;
import cn.ruanyun.backInterface.modules.base.pojo.User;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserService;
import cn.ruanyun.backInterface.modules.base.vo.UserBalanceVo;
import cn.ruanyun.backInterface.modules.business.balance.pojo.Balance;
import cn.ruanyun.backInterface.modules.business.balance.service.IBalanceService;
import cn.ruanyun.backInterface.modules.business.withdrawDeposit.DTO.TransferMoneyDTO;
import cn.ruanyun.backInterface.modules.business.withdrawDeposit.mapper.WithdrawDepositMapper;
import cn.ruanyun.backInterface.modules.business.withdrawDeposit.pojo.WithdrawDeposit;
import cn.ruanyun.backInterface.modules.business.withdrawDeposit.service.IWithdrawDepositService;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import cn.ruanyun.backInterface.common.utils.ToolUtil;
import cn.ruanyun.backInterface.common.utils.SecurityUtil;

import javax.annotation.Resource;


/**
 * 提现管理接口实现
 * @author z
 */
@Slf4j
@Service
@Transactional
public class IWithdrawDepositServiceImpl extends ServiceImpl<WithdrawDepositMapper, WithdrawDeposit> implements IWithdrawDepositService {


       @Autowired
       private SecurityUtil securityUtil;
       @Resource
       private UserMapper userMapper;
       @Autowired
       private IPayService payService;
		@Autowired
		private IBalanceService balanceService;
		@Autowired
		private IUserService userService;

       @Override
       public Result<Object> insertWithdrawDeposit(WithdrawDeposit withdrawDeposit) {

           User user = userMapper.selectById(securityUtil.getCurrUser().getId());
           BigDecimal balance = user.getBalance();
           if(ToolUtil.isNotEmpty(user)){

               //wj提现的钱不能为负数
               if (withdrawDeposit.getMoney().doubleValue() <= 0){

                   return new ResultUtil<>().setErrorMsg(201,"提现金额不能小于0");
               }

               //查询用户的余额够不够申请

	           UserBalanceVo userBalance = userService.getUserBalance();
	           int a = userBalance.getCashBalance().compareTo(withdrawDeposit.getMoney());
               if(a==1||a==0 ){

                   user.setBalance(balance.subtract(withdrawDeposit.getMoney()));
                   userMapper.updateById(user);
                   withdrawDeposit.setCreateBy(securityUtil.getCurrUser().getId());

                   //生成余额明细
	               //生成提现退钱记录
	               Balance balance1 = new Balance();
	               balance1.setTitle("申请提现，扣款")
			               .setAddOrSubtractTypeEnum(AddOrSubtractTypeEnum.SUB)
			               .setPrice(withdrawDeposit.getMoney())
			               .setOrderId(withdrawDeposit.getId())
			               .setCreateBy(user.getId());
	               balanceService.save(balance1);

                   return new ResultUtil<>().setData(this.save(withdrawDeposit),"申请提现成功！");

               }else {
                   return new ResultUtil<>().setErrorMsg(201,"余额不足，申请提现失败！");
               }


           }else {
               return new ResultUtil<>().setErrorMsg(201,"用户信息错误！");
           }


       }


    @Override
    @Transactional
    public Result<Object> UpdateWithdrawDeposit(WithdrawDeposit withdrawDeposit) {

        WithdrawDeposit withdraw = this.getById(withdrawDeposit.getId());

        User user = new User();
        if(ToolUtil.isNotEmpty(withdraw)){
          user = userMapper.selectById(withdraw.getCreateBy());
        }

        //wj 处理审核不通过，跟审核不通过
        if(ToolUtil.isNotEmpty(user)){
        	//审核通过
			if (CommonConstant.NO == withdrawDeposit.getType()){

				withdraw.setType(CommonConstant.NO);
				withdraw.setContent(withdrawDeposit.getContent());
				this.updateById(withdraw);
				//审核通过，修改提现状态，给用户退钱
			}else if (CommonConstant.YES == withdrawDeposit.getType() ){

				//处理提现状态
				withdraw.setType(CommonConstant.YES);
				withdraw.setContent(withdrawDeposit.getContent());
				this.updateById(withdraw);

				//给用户退钱
				user.setBalance(user.getBalance().add(withdraw.getMoney()));
				userMapper.updateById(user);

				//生成提现退钱记录
				Balance balance = new Balance();
				balance.setTitle("提现审核不通过退款")
						.setAddOrSubtractTypeEnum(AddOrSubtractTypeEnum.ADD)
						.setPrice(withdraw.getMoney())
						.setOrderId(withdraw.getId())
						.setCreateBy(user.getId());
				balanceService.save(balance);

			}
	        return new ResultUtil<>().setData(this.updateById(withdraw),"处理提现成功！");

        }else {
            return new ResultUtil<>().setErrorMsg(201,"用户信息错误！");
        }

    }



      @Override
      public void removeWithdrawDeposit(String ids) {

          CompletableFuture.runAsync(() -> this.removeByIds(ToolUtil.splitterStr(ids)));
      }

    /**
     * 后端获取提现记录
     * @param withdrawDeposit
     * @return
     */
      @Override
      public List PcGetWithdrawDeposit(WithdrawDeposit withdrawDeposit) {

//            List<WithdrawDeposit> withdrawDepositList = this.list(new QueryWrapper<WithdrawDeposit>().lambda()
//                .eq((ToolUtil.isNotEmpty(withdrawDeposit.getPayTypeEnum())),WithdrawDeposit::getPayTypeEnum,withdrawDeposit.getPayTypeEnum())
//                .eq((ToolUtil.isNotEmpty(withdrawDeposit.getType())),WithdrawDeposit::getType,withdrawDeposit.getType())
//                .like((ToolUtil.isNotEmpty(withdrawDeposit.getMobile())),WithdrawDeposit::getMobile,withdrawDeposit.getMobile())
//                .like((ToolUtil.isNotEmpty(withdrawDeposit.getWithdrawUser())),WithdrawDeposit::getWithdrawUser,withdrawDeposit.getWithdrawUser())
//            );

          List<WithdrawDeposit> withdrawDepositList = this.baseMapper.selectWithdrList(withdrawDeposit);
           return withdrawDepositList;
      }

    @Override
    public List AppGetWithdrawDeposit(WithdrawDeposit withdrawDeposit) {
        /*  withdrawDeposit.setCreateBy(securityUtil.getCurrUser().getId());
        List<WithdrawDeposit> withdrawDepositList =new ArrayList<>();
        if(null !=withdrawDeposit.getType() && !"".equals(withdrawDeposit.getType())){
            withdrawDepositList=this.baseMapper.selectWithdrListByUserIdAndType(withdrawDeposit.getCreateBy(),withdrawDeposit.getType());
        }else{
            withdrawDepositList=this.baseMapper.selectWithdrListByUserId(withdrawDeposit.getCreateBy());
        }
        return withdrawDepositList;*/

        return Optional.ofNullable(this.list(new QueryWrapper<WithdrawDeposit>().lambda()
                .eq(ToolUtil.isNotEmpty(withdrawDeposit.getType()),WithdrawDeposit::getType,withdrawDeposit.getType())
                .eq(WithdrawDeposit::getCreateBy,securityUtil.getCurrUser().getId())
                .orderByDesc(WithdrawDeposit::getCreateTime)
        )).orElse(null);
    }


}